import React from 'react';
import styles from '@/assets/css/coupon.module.css';
import { PullToRefresh, Loading } from 'antd-mobile';

interface CouponItem {
    id: number;
    cid: number;
    title: string;
    condition: number;
    rate: number;
    limit: number;
    valid_days: number;
    status: string;
    coupon: {
        rate: number;
    };
}

type TabType = 'all' | 'unused' | 'used' | 'inactive';

type CouponLists = Record<TabType, CouponItem[]>;

const Coupon = () => {
    const [couponLists, setCouponLists] = useState<CouponLists>({
        all: [],
        unused: [],
        used: [],
        inactive: []
    });
    const business = React.Cookies.load('business');
    const [activeTab, setActiveTab] = useState<TabType>('all');
    const [loading, setLoading] = useState(false);

    const getCoupons = async () => {
        // 如果该状态下已有数据，就不重新加载
        if (couponLists[activeTab].length > 0) {
            return;
        }

        setLoading(true);
        try {
            const params = {
                id: business.id,
                limit: 10,
                page: 1,
                status: activeTab === 'all' ? '' : activeTab
            }

            const result = await React.Http.post('/Coupon/receive', params);

            if (result.code === 1) {
                // 只更新当前 tab 的数据，保持其他 tab 的数据不变
                setCouponLists(prev => ({
                    ...prev,
                    [activeTab]: result.data.list
                }));
            }
        } catch (error) {
            React.fail('获取优惠券失败');
        } finally {
            setLoading(false);
        }
    }

    // 强制刷新当前 tab 的数据
    const forceRefresh = async () => {
        setLoading(true);
        try {
            const params = {
                id: business.id,
                limit: 10,
                page: 1,
                status: activeTab === 'all' ? '' : activeTab
            }

            const result = await React.Http.post('/Coupon/receive', params);

            if (result.code === 1) {
                setCouponLists(prev => ({
                    ...prev,
                    [activeTab]: result.data.list
                }));
            }
        } catch (error) {
            React.fail('获取优惠券失败');
        } finally {
            setLoading(false);
        }
    }

    useEffect(() => {
        getCoupons();
    }, [activeTab]);

    // 获取当前 tab 的优惠券列表
    const currentCoupons = couponLists[activeTab] || [];

    return (
        <>
            <div className={styles.top}>
                <div>我的优惠券</div>
            </div>
            <div className={styles.coupon_tabs}>
                <li
                    className={activeTab === 'all' ? 'active' : ''}
                    onClick={() => setActiveTab('all')}
                >全部</li>
                <li
                    className={activeTab === 'unused' ? 'active' : ''}
                    onClick={() => setActiveTab('unused')}
                >未使用</li>
                <li
                    className={activeTab === 'used' ? 'active' : ''}
                    onClick={() => setActiveTab('used')}
                >已使用</li>
                <li
                    className={activeTab === 'inactive' ? 'active' : ''}
                    onClick={() => setActiveTab('inactive')}
                >未生效</li>
            </div>
            <PullToRefresh onRefresh={forceRefresh}>
                {loading ? (
                    <div className={styles.loading_container}>
                        <Loading color='primary' />
                        <span>加载中...</span>
                    </div>
                ) : (
                    <div className={styles.coupon_list}>
                        {currentCoupons.length === 0 ? (
                            <div className={styles.no_coupon}>暂无优惠券</div>
                        ) : (
                            currentCoupons.map((coupon, index) => (
                                <div className={styles.coupon_item} key={index}>
                                    <div className={styles.item_content}>
                                        <NavLink to={`/business/CouponInfo?cid=${coupon.cid}`}>
                                            <div className={styles.left}>
                                                {coupon.coupon.rate}<span>折</span>
                                            </div>
                                            <div className={styles.right}>
                                                <div>{coupon.title || '优惠券'}</div>
                                                <div>订单打<span>{coupon.rate || 8}折</span></div>
                                                <div>每人限领{coupon.limit || 1}张</div>
                                                <div>{coupon.valid_days ? `领取后${coupon.valid_days}天内有效` : '有效期未知'}</div>
                                            </div>
                                        </NavLink>
                                    </div>
                                    <React.UI.Button color={coupon.status === '1' ? 'danger' : 'default'} disabled={coupon.status === '0'} size="mini">
                                        待使用
                                    </React.UI.Button>
                                </div>
                            ))
                        )}
                    </div>
                )}
            </PullToRefresh>
        </>
    )
}

export default Coupon;